package com.qf.springbootopenapi.filter;

import com.qf.springbootopenapi.utils.Constants;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
@WebFilter("/logout")
public class LogoutFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("================LogoutFilter 初始化成功！================");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        
        // 注销当前用户
        log.debug("删除session中的user对象");
        HttpSession session = req.getSession();
        session.setAttribute(Constants.USER_SESSION_KEY, null);
        
        log.debug("删除浏览器中的UserToken");
        Cookie userTokenCookie = new Cookie(Constants.USER_TOKEN, "");
        userTokenCookie.setMaxAge(0);
        userTokenCookie.setPath("/");
        resp.addCookie(userTokenCookie);
        
        //重定向到login.html
        resp.sendRedirect("/login.html");
    }
    
    @Override
    public void destroy() {
        log.debug("================LogoutFilter 销毁成功！================");
        
    }
}
